package com.couldsail.takeaway.handler;

import com.couldsail.takeaway.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    /*@ExceptionHandler
    public Result globalExceptionHandler(Exception  ex) {
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }*/
    /*@ExceptionHandler
    public Result globalExceptionAll(Exception ex){
        System.out.println("发生未知错误");
        String message = ex.getMessage();
        System.out.println(message);
        System.out.println(message.contains("Duplicate entry"));
        return Result.error("服务器未知错误!");
    }*/
    /**
     * 处理 SQL 相关的异常
     * @param ex
     * @return
     */
//    @ExceptionHandler
//    private Result handleSqlException(DataAccessException ex) {
//        log.error("sql执行异常{}",ex.getMessage());
//        //### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '张三' for key 'idx_username'
//        String message = ex.getMessage();
//        if(message.contains("Duplicate entry")){
//            String[] split = message.split(" ");
//            String username = split[9];
//            String msg = username + MessageConstant.ALREADY_EXISTS;
//            return Result.error(msg);
//        }else{
//            return Result.error(MessageConstant.UNKNOWN_ERROR);
//        }
//    }

    /**
     * 处理其他类型的异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    private Result handleOtherException(Exception ex) {
        log.error("Exception异常全局捕获");
        log.error(ex.getMessage());
        return Result.error(ex.getMessage());
    }
}
